const Koa = require('koa');
const app = new Koa()
const path = require('path')
app.use(require('koa-static')(path.join(__dirname, 'static')));
const server = require('http').createServer(app.callback());
const io = require('socket.io')(server);
const child_process = require('child_process')
const process = require('process')

child_process.exec('nc -zvw3 127.0.0.1 6379', (err, stdout, stderr) => {
    if (!err) {
        // console.log('stdout:', stdout)
        // console.log('stderr:', stderr)
        if (stderr.indexOf('succeeded') === -1) {
            console.log('你没有开启redis服务，请开启！')
            process.exit()
        } else {
            console.log('检测到你开通了redis服务')
        }
    } else {
        console.log('child_process error:', err)
        process.exit()
    }
})
const wrapperObj = []
io.on('connection', async (socket) => { 
    console.log('some on connection')
    socket.on('createRoom', (data) => {
        console.log('get create room')
        console.log('data:', data)
        data = JSON.parse(data)
        // 创建房间
        socket.join(data.roomId)
        wrapperObj.push(data)
        setTimeout(() => {
            const rooms = io.of("/").adapter.rooms;
            console.log('rooms:', rooms)
            console.log('wrapperObj:', wrapperObj)
        }, 1000)
    })
    socket.on('answer', data => {
        socket.emit('answer', data)
    })
    socket.on("disconnect", (reason) => {
        console.log('disconnect reason:', reason)
    })
    socket.on('control', async data => {
        data = JSON.parse(data)
        // 根据序列号找到相关账户的signal，要进行密码校验
        console.log('connect data:', data)
        const waitConnectUser = wrapperObj.filter(item => item.number === data.number)
        console.log('waitConnectUser:', waitConnectUser)
        // return all Socket instances
        const socket = await getSocketById(waitConnectUser[0].roomId)
        socket.emit("puppet", {controlId: socket.id, offer: data.signal})
    })

    // 傀儡上传自己的signal
    socket.on('push-puppet-answer', async data => {
        console.log('get push-puppet-answer:', data)
        // const controlSocket = await getSocketById(data.controlId)
        // 去控制方的房间发送消息
        io.emit('answer', data.answer)
    })


});
// socket.emit("puppet-signal", waitConnectUser[0].signal)

// 根据id找到指定的socket
async function getSocketById (id) {
    const sockets = await io.fetchSockets();
    // console.log('sockets:', sockets)
    let _socket
    sockets.forEach(socket => {
        console.log('current id:', socket.id)
        if (socket.id === id) {
            _socket = socket
        }
    })
    if (!_socket) {
        console.error('指定id的socket没有找到')
    }
    return _socket
}

// 监听room的创建
io.of("/").adapter.on("create-room", (room) => {
    console.log(`room ${room} was created`);
});

server.listen(3000);